import { connect } from 'react-redux'
import { createRef } from 'react'
import { 
	Modal,
	Form,
	Input,
	Checkbox,
	message,
} from 'antd'

import { changeLog, changeUserInfo } from '../../store/actions'
import { postUserLogin } from '../../assets/js/api'
import { setToken } from '../../assets/js/tools'

import './index.css'
import { getSocket } from '../../socketEvent'

function Login(props) {
	const {
		changeLog,
		changeUserInfo,

		closeLogPopup,
		showRegPopup,
		logIn,
	} = props;

	const form = createRef();
	const initFormVal = {username: '', password: '', remember: false};

	function close() {
		// 关闭登录框
		form.current.resetFields();
		closeLogPopup();
	}
	function validatorForm() {
		// 验证表单
		form.current.validateFields()
		.then(val => {
			// 用户登录
			postUserLogin(val)
			.then(res => {
				const {code, message: content, data, token} = res.data;
				if (code === 1) {
					// 登录成功
					if (token) {
						setToken('token', token);
					}
					message.success({content, duration: 2});
					getSocket(res.data.data.id);
					changeUserInfo(data);
					changeLog(true);
					closeLogPopup();
					logIn();
				} else if (code === 0) {
					message.error(content);
				} else {
					console.log(res.data)
					message.error('一个意外的错误,请稍后重试');
				}
			})
			.catch(err => {
				console.log(err);
				message.error(err);
			});
		})
		.catch(err => {
			console.log(err)
		});
	}
	function keyEvent(e) {
		if (e.keyCode === 13) {
			validatorForm();
		}
	}

    return (
		<Modal 
			title="登录" 
			cancelText="取消"
			okText="登录"
			className="login_popup"
			centered={true}
			visible={props.show} 
			maskClosable={false}
			onOk={validatorForm} 
			onCancel={close}
		> 
			<Form
				ref={form}
				initialValues={initFormVal}
				scrollToFirstError={true}
				onKeyUp={keyEvent}
			>
				<Form.Item
					label="账号"
					name="account"
					rules={[{ required: true, message: '请输入账号' }]}
				>
					<Input />
				</Form.Item>
				<Form.Item
					label="密码"
					name="password"
					rules={[{ required: true, message: '请输入密码' }]}
				>
					<Input type="password" />
				</Form.Item>
				<Form.Item>
					<Form.Item className="tools_box" name="remember" valuePropName="checked" noStyle>
						<Checkbox className="check">Remember me</Checkbox>
					</Form.Item>
					<a href="" className="register" onClick={showRegPopup}>注册</a>
				</Form.Item>
			</Form>
		</Modal>
    )
}

function mapStateToProps(state) {
    return {
        islogin: state.islogin
    }
}


export default connect(
	mapStateToProps, 
	{
		changeLog,
		changeUserInfo,
	}
)(Login);

